import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import api from '@/api/home'
import type { HashSet } from '@/config/types'

interface LineData {
    categories: string[]
    datas: HashSet<number[]>
}

export const useHomeStore = defineStore('home', () => {
    const loading = ref<boolean>(false)
    const todayLogin = ref<number>(0)
    const totalLogin = ref<number>(0)
    const loginPercent = computed<number>(() => {
        return totalLogin.value > 0 ? Math.round(todayLogin.value / totalLogin.value * 100) : 0
    })
    const todayRegister = ref<number>(0)
    const totalRegister = ref<number>(0)
    const registerPercent = computed<number>(() => {
        return totalRegister.value > 0 ? Math.round(todayRegister.value / totalRegister.value * 100) : 0
    })
    const onselfLessons = ref<number>(0)
    const totalLessons = ref<number>(0)
    const lessonPercent = computed<number>(() => {
        return totalLessons.value > 0 ? Math.round(onselfLessons.value / totalLessons.value * 100) : 0
    })
    const todayOrders = ref<number>(0)
    const totalOrders = ref<number>(0)
    const orderPercent = computed<number>(() => {
        return totalOrders.value > 0 ? Math.round(todayOrders.value / totalOrders.value * 100) : 0
    })

    const loginDatas = ref<LineData>({
        categories: ['6-10', '6-9', '6-8', '6-7', '6-6', '6-5', '6-4'],
        datas: {
            '注册人数': [12, 15, 8, 17, 22, 19, 18],
            '登录人数': [12, 15, 8, 17, 22, 19, 18]
        }
    })

    const orderDatas = ref<LineData>({
        categories: ['6-10', '6-9', '6-8', '6-7', '6-6', '6-5', '6-4'],
        datas: {
            '订单数': [12, 15, 8, 17, 22, 19, 18]
        }
    })

    async function getHomeData() {
        loading.value = true
        try {
            const res = await api.get()
            todayLogin.value = res.data.todayLogin
            totalLogin.value = res.data.totalLogin
            todayRegister.value = res.data.todayRegister
            totalRegister.value = res.data.totalRegister
            onselfLessons.value = res.data.onselfLessons
            totalLessons.value = res.data.totalLessons
            todayOrders.value = res.data.todayOrders
            totalOrders.value = res.data.totalOrders
            loginDatas.value = res.data.loginDatas
            orderDatas.value = res.data.orderDatas
        } finally {
            loading.value = false
        }
    }
    
    return {
        loading,
        todayLogin,
        totalLogin,
        loginPercent,
        todayRegister,
        totalRegister,
        registerPercent,
        onselfLessons,
        totalLessons,
        lessonPercent,
        todayOrders,
        totalOrders,
        orderPercent,

        loginDatas,
        orderDatas,
        getHomeData
    }
})